package com.softa.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

/**
 * Created by yangl on 2017/8/5.
 */
public class FtpUtil {

    private static Logger logger = Logger.getLogger(FtpUtil.class);

    private static FTPClient ftpClient;


    /**
     * 获取ftp连接
     * @param f  ftp连接对象
     */
    public static boolean connectFtp(Ftp f)  {
        boolean flag = false;
        try {
            ftpClient = new FTPClient();
            //连接FTP服务器
            //默认端口21
            if (f.getPort() == null){
                ftpClient.connect(f.getIpAddr(), 21);
            }
            else{
                ftpClient.connect(f.getIpAddr(), f.getPort());
            }
            //登陆ftp服务器
            ftpClient.login(f.getUserName(), f.getPwd());
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            //验证FTP服务器是否登录成功
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
            }
            //切换FTP目录
            ftpClient.changeWorkingDirectory(f.getPath());
            flag = true;
        } catch (IOException e) {
            flag = false;
            e.printStackTrace();
        }finally {
           logger.info("ftp链接-------登陆状态："+flag);
        }
        return flag;
    }

    /**
     * 关闭ftp连接
     */
    public static void closeFtp(){
        if (ftpClient != null && ftpClient.isConnected()){
            try{
                ftpClient.logout();
                ftpClient.disconnect();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        logger.info("ftp注销登陆");
    }


    /**
     * 上传文件（可供Action/Controller层使用）
     * @param fileName 上传到FTP服务器后的文件名称
     * @param inputStream 输入文件流
     * @return
     */
    public static boolean uploadFile(Ftp ftp, String fileName, InputStream inputStream){
        boolean flag = false;
        try {
            boolean isconnect = connectFtp(ftp);
            if(isconnect){
                ftpClient.setControlEncoding("UTF-8");
                ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
                ftpClient.makeDirectory(ftp.getPath());
                ftpClient.storeFile(fileName, inputStream);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try {
                if(null != inputStream){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            //关闭注销
            closeFtp();
        }
        return flag;
    }


    /**
     * 上传文件（可对文件进行重命名）
     * @param fileName 上传到FTP服务器后的文件名称
     * @param originfileName 待上传文件的名称（绝对地址）
     * @return
     */
    public static boolean uploadFileFromProduction(Ftp ftp, String fileName, String originfileName){
        boolean flag = false;
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(originfileName));
            flag = uploadFile(ftp, fileName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != inputStream){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 上传文件（不可以进行文件的重命名操作）
     * @param originfileName 待上传文件的名称（绝对地址）
     * @return
     */
    public static boolean uploadFileFromProduction(Ftp ftp, String originfileName){
        boolean flag = false;
        InputStream inputStream = null;
        try {
            String fileName = new File(originfileName).getName();
            inputStream = new FileInputStream(new File(originfileName));
            flag = uploadFile(ftp, fileName, inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != inputStream){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 删除文件
     * @param fileName 要删除的文件名称
     * @return
     */
    public static boolean deleteFile(Ftp ftp, String fileName){
        boolean flag = false;
        try {
            boolean isconnect = connectFtp(ftp);
            if(isconnect){
                ftpClient.dele(fileName);
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            //关闭注销
            closeFtp();
        }
        return flag;
    }

    /**
     * 下载文件
     * @param fileName 文件名称
     * @param localPath 下载后的文件路径
     * @return
     */
    public static boolean downloadFile(Ftp ftp, String fileName, String localPath){
        boolean flag = false;
        try {
            boolean isconnect = connectFtp(ftp);
            if(isconnect){
                FTPFile[] ftpFiles = ftpClient.listFiles();
                for(FTPFile file : ftpFiles){
                    if(fileName.equalsIgnoreCase(file.getName())){
                        File localFile = new File(localPath + "/" + file.getName());
                        OutputStream os = new FileOutputStream(localFile);
                        ftpClient.retrieveFile(file.getName(), os);
                        os.close();
                    }
                }
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
                //关闭注销
                closeFtp();
        }
        return flag;
    }

    public static void main(String[] args) {
        Ftp f = new Ftp();
        f.setIpAddr("192.168.101.134");
        f.setPort(21);
        f.setUserName("ftpuser");
        f.setPwd("123456");
        f.setPath("/var/www/html");
        //上传
        FtpUtil.uploadFileFromProduction(f, "123.xml", "D:\\software\\solr.xml");
        //下载
//        FtpUtil.downloadFile(f, "solr.xml", "D:/");
        //删除
        FtpUtil.deleteFile(f, "123.xml");
    }

}
